package com.szcinda.service.dto.vehicle;

import com.szcinda.repository.Vehicle;
import com.szcinda.repository.VehicleRepository;
import com.szcinda.service.SnowFlakeFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

@Service
@Transactional
public class VehicleServiceImpl implements VehicleService {
    private final VehicleRepository vehicleRepository;
    private final SnowFlakeFactory snowFlakeFactory;

    public VehicleServiceImpl(VehicleRepository vehicleRepository) {
        this.vehicleRepository = vehicleRepository;
        this.snowFlakeFactory = SnowFlakeFactory.getInstance();
    }

    @Override
    public void create(CreateVehicleDto createVehicleDto) {
        Vehicle vehicle = vehicleRepository.findByName(createVehicleDto.getName());
        Assert.isTrue(vehicle == null, "存在相同车型的记录");
        vehicle = new Vehicle();
        BeanUtils.copyProperties(createVehicleDto, vehicle);
        vehicle.setId(snowFlakeFactory.nextId("VE"));
        vehicleRepository.save(vehicle);
    }

    @Override
    public void update(UpdateVehicleDto updateVehicleDto) {
        Vehicle vehicle = vehicleRepository.findFirstById(updateVehicleDto.getId());
        vehicle.setName(updateVehicleDto.getName());
        vehicle.setDeliveryFee(updateVehicleDto.getDeliveryFee());
        vehicle.setFrontPickFee(updateVehicleDto.getFrontPickFee());
        vehicleRepository.save(vehicle);
    }

    @Override
    public void delete(String id, String userId) {
        vehicleRepository.delete(id);
    }

    @Override
    public List<Vehicle> findAll() {
        return vehicleRepository.findAll();
    }

    @Override
    public void batchCreate(List<VehicleImportDto> importDatas, String opId) {
        List<Vehicle> vehicles = vehicleRepository.findAll();
        for (VehicleImportDto importData : importDatas) {
            boolean b = vehicles.stream().noneMatch(vehicle -> vehicle.getName().equals(importData.getName()));
            if (b) {
                Vehicle vehicle = new Vehicle();
                BeanUtils.copyProperties(importData, vehicle);
                if (importData.getFrontPickFee() != null) {
                    vehicle.setFrontPickFee(importData.getFrontPickFee());
                }
                if (importData.getDeliveryFee() != null) {
                    vehicle.setDeliveryFee(importData.getDeliveryFee());
                }
                vehicle.setId(snowFlakeFactory.nextId("VE"));
                vehicleRepository.save(vehicle);
            }
        }
    }
}
